package com.siruier.boss.ui.fragment

import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.dingmouren.layoutmanagergroup.viewpager.OnViewPagerListener
import com.dingmouren.layoutmanagergroup.viewpager.ViewPagerLayoutManager
import com.kingja.loadsir.core.LoadService
import com.siruier.boss.ad.AdBean
import com.siruier.boss.ad.AdSdk
import com.siruier.boss.ad.VideoPayTimeTimer
import com.siruier.boss.api.core.launchUI
import com.siruier.boss.api.loginApi
import com.siruier.boss.databinding.FragmentAdVideoTaskBinding
import com.siruier.boss.databinding.ItemAdTestBinding
import com.siruier.boss.ui.api.ApiObserver
import com.siruier.boss.ui.base.BaseFragment
import com.siruier.boss.ui.base.BaseRecyclerAdapter
import com.siruier.boss.ui.helper.loadsir.LoadSirHelper
import com.siruier.boss.ui.utils.Logger
import kotlinx.coroutines.delay
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume

class AdVideoTaskFragment : BaseFragment<FragmentAdVideoTaskBinding>() {
    private lateinit var mLoadService: LoadService<*>
    private val mAdTestAdapter = AdTestAdapter()
    private var currentPosition = 0
    private var currentCompletedPosition: Int? = null

    override fun initView(rootView: View?, savedInstanceState: Bundle?) {
        mLoadService = LoadSirHelper.register(vb.rvList)
        vb.rvList.layoutManager = ViewPagerLayoutManager(context, LinearLayoutManager.VERTICAL).apply {
            setOnViewPagerListener(object : OnViewPagerListener {
                override fun onInitComplete() {

                }

                override fun onPageRelease(p0: Boolean, position: Int) {
                    Logger.e("onPageRelease==>${position}")
                    VideoPayTimeTimer.stopTimer(mAdTestAdapter.getItem(position).unKey)
                }

                override fun onPageSelected(position: Int, p1: Boolean) {
                    Logger.e("onPageSelected==>${position}")
                    currentPosition = position
                    VideoPayTimeTimer.startTimer(mAdTestAdapter.getItem(position).unKey)
                }
            })
        }
        vb.rvList.adapter = mAdTestAdapter
        AdSdk.adVideoCompleted = {
            Logger.e("currentPosition==>${currentPosition}")
            currentCompletedPosition = currentPosition
            if (!isHidden) {
                scrollNext()
            }
            launchUI({ checkAdNum() }, ApiObserver(context, showLoadingDialog = false))
            if (it) {
                launchUI({ loginApi.taskVrd(System.currentTimeMillis()) })
            }
        }
        vb.rvList.post {
            loadAd(mLoadService)
        }
        VideoPayTimeTimer.startTimer()
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!isHidden) {
            scrollNext()
        }
    }

    private fun loadAd(loadService: LoadService<*>? = null) {
        launchUI({
            AdSdk.sdkInit(requireContext())
            if (!loadAdToAdapter()) {
                // 没有加载到广告，开启定时器一直刷
                while (true) {
                    delay(10000)
                    if (loadAdToAdapter()) {
                        break
                    }
                }
            }
        }, ApiObserver(loadService = loadService))
    }

    private suspend fun loadAdToAdapter(): Boolean {
        Logger.e("广告拉取开始")
        val ads = AdSdk.loadExpressDrawNativeAd(requireContext(), vb.rvList.measuredWidth, vb.rvList.measuredHeight)
        Logger.e("广告拉取条数==》${ads.size}")
        if (ads.isNotEmpty()) {
            val itemCount = mAdTestAdapter.itemCount
            mAdTestAdapter.addAll(ads)
            VideoPayTimeTimer.startFirst(ads[0].unKey)
            // 拉取成功如果当前看完的就是最后一条需要自动往下滚
            if (currentCompletedPosition == itemCount - 1) {
                vb.rvList.scrollToPosition(currentPosition + 1)
            }
        }
        return ads.isNotEmpty()
    }

    private fun scrollNext() {
        // 没到最后一个自动轮播下一个
        if (currentCompletedPosition != null && currentPosition + 1 < mAdTestAdapter.datas.size) {
            currentPosition++
            vb.rvList.scrollToPosition(currentPosition)
            VideoPayTimeTimer.startTimer(mAdTestAdapter.getItem(currentPosition).unKey)
        }
    }

    private suspend fun checkAdNum() {
        // 到最后一个了，如果太多了清理一下
        if (mAdTestAdapter.itemCount >= 100 && currentCompletedPosition == mAdTestAdapter.itemCount - 1) {
            mAdTestAdapter.datas.forEach(AdSdk::adDestroy)
            mAdTestAdapter.datas.clear()
            mAdTestAdapter.notifyDataSetChanged()
            suspendCancellableCoroutine { coroutine ->
                vb.rvList.post {
                    coroutine.resume(Unit)
                }
            }
        }
        if (mAdTestAdapter.itemCount - currentPosition <= 3) {
            loadAd()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        AdSdk.adVideoCompleted = null
        mAdTestAdapter.datas.forEach(AdSdk::adDestroy)
        VideoPayTimeTimer.destroyTimer()
    }
}

class AdTestAdapter : BaseRecyclerAdapter<ItemAdTestBinding, AdBean>() {
    override fun onBindViewHolder(vb: ItemAdTestBinding, bean: AdBean, position: Int) {
        vb.videoLayout.removeAllViews()
        val view = bean.view
        if (view.parent != null) {
            (view.parent as ViewGroup).removeView(view)
        }
        vb.videoLayout.addView(view)
    }
}